package xin.sunzy.spring.util;

import xin.sunzy.spring.model.User;

import java.util.Locale;

/**
 * @description: 用户工具类
 * @email: <a href="sunzhenyu@terminus.io">孙振宇</a>
 * @author: ginkgo
 * @date: 2018/4/2
 */
public final class UserUtils {

    /**
     * 保存线程独占的变量 user
     */
    private static ThreadLocal<User> user = new ThreadLocal<>();

    /**
     * 用于保存用户的语言选择
     */
    private static ThreadLocal<Locale> locale = new ThreadLocal<>();

    /**
     * 存放当前线程的用户
     *
     * @param user
     */
    public static void putCurrentUser(User user) {
        UserUtils.user.set(user);
    }

    /**
     * 保存用户的语言选择
     *
     * @param locale
     */
    public static void putCurrentLocale(Locale locale) {
        UserUtils.locale.set(locale);
    }

    /**
     * 获取当前线程的用户
     *
     * @return
     */
    public static <T extends User> T getCurrentUser() {
        return (T) user.get();
    }
    /**
     * 获取用户的语言选择
     *
     * @return
     */
    public static Locale getCurrentLocale() {
        return locale.get();
    }
    /**
     * 释放内存，避免内存泄漏
     */
    public static void clearCurrentUser() {
        user.remove();
        locale.remove();
    }

    /**
     * 获取当前线程用户的 ID
     *
     * @return
     */
    public static Long getUserId() {
        User baseUser = user.get();
        return null != baseUser ? baseUser.getId() : null;
    }
}
